package top.houry.im.client.netty;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import top.houry.im.client.enums.ImClientMsgTypeProcessorEnum;
import top.houry.im.client.event.ImClientUiLoginEvent;
import top.houry.im.client.handler.ImClientMsgTypeHandler;
import top.houry.im.client.handler.impl.ImClientHeartBeatHandlerImpl;
import top.houry.im.client.proto.ImMessage;
import top.houry.im.client.utils.ImClientChannelUtils;


public class ImClientNettyHandler extends SimpleChannelInboundHandler<ImMessage.Client> {

    private static final Logger log = LoggerFactory.getLogger(ImClientNettyHandler.class);

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ImMessage.Client client) throws Exception {
        ImClientMsgTypeHandler handler = (ImClientMsgTypeHandler) ImClientMsgTypeProcessorEnum.findByMsgType(client.getMsgType()).getClazz();
        handler.processImMsg(client, ctx);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ImClientChannelUtils.addChannelHandlerContext(ctx);
//        new ImClientHeartBeatHandlerImpl().sendHeartBeatMsg(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {

    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            switch (event.state()) {
                case READER_IDLE:
                    log.info("[ImClientNettyHandler]-[userEventTriggered]-[没有接收到：{}]-[的信息心跳信息，将断开连接回收资源]", ctx.toString());
                    ctx.channel().close();
                    break;
                case WRITER_IDLE:
                    log.info("[ImClientNettyHandler]-[userEventTriggered]-[写空闲]");
                    break;
                case ALL_IDLE:
                    log.info("[ImClientNettyHandler]-[userEventTriggered]-[读写空闲]");
                    break;
                default:
                    log.info("[ImClientNettyHandler]-[userEventTriggered]-[非法状态]");
                    throw new IllegalStateException("非法状态！");
            }
        }
    }
}
